package com.UdpRecieve.Netty;

import com.UdpRecieve.Netty.codec.DecodeHandler;
import com.UdpRecieve.Netty.codec.EncodeHandler;
import com.UdpRecieve.Netty.server.handler.FilePacketServerHandler;
import com.UdpRecieve.Netty.server.handler.FileReceiveServerHandler;
import com.UdpRecieve.Netty.server.handler.FileSendServerHandler;
import com.UdpRecieve.Netty.server.handler.JoinClusterRequestHandler;
import com.UdpRecieve.tool.Global;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class NettyOwnServer implements CommandLineRunner {

	private int port = 8090;
	private ServerBootstrap bootstrap = new ServerBootstrap();
	Logger logger = LoggerFactory.getLogger(NettyOwnServer.class);
	public NettyOwnServer(){

		EventLoopGroup boss = new NioEventLoopGroup();
		EventLoopGroup worker = new NioEventLoopGroup();

		bootstrap.group(boss, worker)
				.channel(NioServerSocketChannel.class)
				.option(ChannelOption.SO_BACKLOG, 50)//服务端接受连接的队列长度
				.option(ChannelOption.SO_KEEPALIVE, true)
				.option(ChannelOption.TCP_NODELAY, true)//禁用nagle算法
				.childHandler(new ChannelInitializer<NioSocketChannel>() {
					@Override
					protected void initChannel(NioSocketChannel channel) throws Exception {
						ChannelPipeline pipeline = channel.pipeline();
						pipeline.addLast("length",new LengthFieldBasedFrameDecoder(65535,5,4,0,0));
						pipeline.addLast(new FileReceiveServerHandler());
						pipeline.addLast(new FileSendServerHandler());
						pipeline.addLast(new DecodeHandler());
						pipeline.addLast(new EncodeHandler());
						pipeline.addLast(new JoinClusterRequestHandler());
						pipeline.addLast(new FilePacketServerHandler());


					}
				});
		logger.info("Netty类已经初始化");
	}

	public void start (){
		try {
			ChannelFuture future = bootstrap.bind(port).sync();

			if (future.isSuccess()) {
				System.out.println("netty server 启动完毕,端口"+port+"绑定成功");
			} else {
				System.out.println("netty server 端口绑定失败");
			}
			future.channel().closeFuture().sync();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run(String... args) throws Exception {
		String isStart = Global.getConfig("Netty.isStart");
		if ("true".equals(isStart)){
			start();
		}else {
			logger.info("该项目未开启Netty!");
		}
	}
}
